package cc.iotkit.manager.task;

import cc.iotkit.common.thing.ThingModelMessage;
import cc.iotkit.common.utils.JsonUtils;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.manager.IDeviceDailyReportData;
import cc.iotkit.model.device.DeviceDailyReport;
import cc.iotkit.temporal.IThingModelMessageData;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/***
 * 分析属性上报数据
 */
@Component
public class AnalysisAttributeReport {
    @Autowired
    private IThingModelMessageData thingModelMessageData;

    @Autowired
    private IDeviceDailyReportData deviceDailyReportData;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private String LastTimeCacheKey="sync:analysis_attribute_report";
    private static Logger logger = LoggerFactory.getLogger(AnalysisAttributeReport.class);

    @XxlJob("AnalysisAttributeReport")
    public void run() {
        logger.info("xxl-job:running AnalysisAttributeReport...");
        try {
            String startTime=getLastTime();
            String endTime=LocalDateTime.now().toString();
            List<ThingModelMessage> messageList = thingModelMessageData.findReports(startTime, endTime);
            List<DeviceDailyReport> reports = new ArrayList<>();
            messageList.forEach(m -> {
                DeviceDailyReport r = JSONUtil.toBean(StrUtil.toCamelCase(m.getData().toString()), DeviceDailyReport.class);
                r.setDeviceId(m.getDeviceId());
                r.setReportDate(new Date(m.getTime()));
                reports.add(r);
            });

            deviceDailyReportData.batchSave(reports);
            this.setLastTime(endTime);
            logger.info("xxl-job:running AnalysisAttributeReport finished");
        }
        catch (Exception e){
            logger.info("xxl-job-error:"+e.getMessage());
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail();
        }
        /*XxlJobHelper.log("XXL-JOB, Hello World.");

        for (int i = 0; i < 5; i++) {
            XxlJobHelper.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }*/
    }

    public String getLastTime() {
        Object last = redisTemplate.opsForValue().get(LastTimeCacheKey);
        if(ObjectUtils.isEmpty(last)){
            Calendar c = Calendar.getInstance();
            return LocalDateTime.of(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH),0,0,0,1).toString();
        }
        return last.toString();
    }

    public void setLastTime(String lastTime) {
        redisTemplate.opsForValue().set(LastTimeCacheKey, lastTime);
    }
}
